//
//  HZPeiziHomeViewController.m
//  Stock_Stategy
//
//  Created by MayerF on 2017/11/23.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZPeiziHomeViewController.h"
#import "HZPeiziHomeView.h"
#import "MYHttp.h"

@interface HZPeiziHomeViewController ()
@property (nonatomic, strong)HZPeiziHomeView *pPeiziHomeView;
@property (nonatomic, strong)NSArray *pAccounts;
@property (nonatomic, copy)NSString *pCurAccountId;
@property (nonatomic, strong)HZPeiziAccountMoneyModel *pMoneyModel;
@end

@implementation HZPeiziHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //关联逻辑管理对象
    self.logicManager = [HZBaseLogjcManager new];
    self.view.logicManager = self.logicManager;
    
    _pPeiziHomeView = [HZPeiziHomeView new];
    [self.view addSubview:_pPeiziHomeView];
    [_pPeiziHomeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
    [self p_registerBlock];
    
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (!_pCurAccountId) {
        [self p_requestPeiziAccount];
    }else {
//        [self p_requestPeiziAccountSessionWithAccountid:_pCurAccountId];
        [self p_requestCapitalInfo];
    }
}
- (void)updateTitle:(NSString *)title
{
    self.title = title;
}

#pragma mark -
#pragma mark blockAction
- (void)p_registerBlock
{
    __weak typeof (self)weakSelf = self;
    [self.logicManager mapLogic:kLogicRouterPeiziAccountMoney toBlock:^id(NSDictionary *params, id other) {
        id obj = weakSelf.pMoneyModel;
        if (!weakSelf.pMoneyModel) {
            obj = @"";
        }
        UIViewController *nextVC = [[MYRouter shared] matchController:kRouterPeiziAccountMoney params:@{@"param": obj}];
        [weakSelf.navigationController pushViewController:nextVC animated:YES];
        return nil;
    }];
    [self.logicManager mapLogic:kLogicRouterPeiziBuySell toBlock:^id(NSDictionary *params, id other) {
        if (!_pCurAccountId) { return nil;}
        NSDictionary *dict = nil;
        if ([other isEqual:@"买入"]) {
            dict = @{@"type": @(1)};
        }else {
            dict = @{@"type": @(2)};
        }
        UIViewController *nextVC = [[MYRouter shared] matchController:kRouterPeiziBuySell params:dict];
        [weakSelf.navigationController pushViewController:nextVC animated:YES];
        return nil;
    }];
    [self.logicManager mapLogic:kLogicRouterPeiziCancelOrder toBlock:^id(NSDictionary *params, id other) {
        if (!_pCurAccountId) { return nil;}
        UIViewController *nextVC = [[MYRouter shared] matchController:kRouterPeiziCancelOrder];
        [weakSelf.navigationController pushViewController:nextVC animated:YES];
        return nil;
    }];
    [self.logicManager mapLogic:kLogicRouterPeiziClickList toBlock:^id(NSDictionary *params, id other) {
        if (!_pCurAccountId && ![other isEqual:@"更多账户"]) { return nil;}
        if ([other isEqual:@"更多账户"]) {
            [weakSelf showMoreAccount];
            return nil;
        }
        UIViewController *nextVC = [[MYRouter shared] matchController:other params:@{@"accountId": _pCurAccountId, @"money": _pMoneyModel}];
        [weakSelf.navigationController pushViewController:nextVC animated:YES];
        return nil;
    }];
}

- (void)showMoreAccount
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请选择账户" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [self addDynamicAccountWithAlertVC:alertVC];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
//    [cancel setValue:kMYHexToRGB(0xff4040, 1) forKey:@"titleTextColor"];
    [alertVC addAction:cancel];
    [self presentViewController:alertVC animated:YES completion:nil];
    
    NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"请选择账户"];
    [hogan addAttribute:NSFontAttributeName
                  value:[UIFont systemFontOfSize:17]
                  range:NSMakeRange(0, hogan.length)];
    [hogan addAttribute:NSForegroundColorAttributeName value:kMYHexToRGB(0x333333, 1) range:NSMakeRange(0, hogan.length)];
    [alertVC setValue:hogan forKey:@"attributedTitle"];
}
- (void)addDynamicAccountWithAlertVC:(UIAlertController *)alertVC
{
    [self.pAccounts enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HZPeiziAccountModel *model = (HZPeiziAccountModel *)obj;
        NSString *tempId = model.contract_id;
        if ([model.contract_status isEqual:@"1"]) {
            tempId = [NSString stringWithFormat:@"%@(已解约)",model.contract_id];
        }
//        if (![model.contract_id isEqual:_pCurAccountId]) {
            UIAlertAction *account = [UIAlertAction actionWithTitle:tempId style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                [self dismissViewControllerAnimated:YES completion:nil];
                [self p_requestPeiziAccountSessionWithAccountid:model.contract_id];
            }];
            [alertVC addAction:account];
//        }
    }];
}

#pragma request
// 配资账户信息
- (void)p_requestPeiziAccount
{
    [SVProgressHUD show];
    [HZApiManager apiPostParams:@{kAPIFuctionKey: @"300034"} success:^(id objc) {
        if ([objc isKindOfClass:[NSArray class]]) {
            NSMutableArray *tempArray = [NSMutableArray array];
            NSArray *result = (NSArray *)objc;
            __block NSString *firstid = nil;
            if (result.count > 0) {
                [result enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    HZPeiziAccountModel *model = [HZPeiziAccountModel mj_objectWithKeyValues:obj];
                    [tempArray addObject:model];
                    if (idx == 0) {
                        firstid = model.contract_id;
                    }
                }];
            }else {
                [HZUserManager manager].isVip = NO;
            }
            _pAccounts = tempArray;
            
            [self p_requestPeiziAccountSessionWithAccountid:firstid];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
- (void)p_requestPeiziAccountSessionWithAccountid:(NSString *)accountid
{
    [SVProgressHUD show];
    [HZApiManager apiPostParams:@{kAPIFuctionKey: @"300037", @"contract_id": accountid} success:^(id objc) {
        if ([objc isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict = (NSDictionary *)objc;
            if ([dict.allKeys containsObject:@"eam_session"]) {
                [HZUserManager manager].peiziAccountSession = dict[@"eam_session"];
                _pCurAccountId = accountid;
                [self p_requestCapitalInfo];
            }
        }
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}
- (void)p_requestCapitalInfo
{
    [SVProgressHUD show];
    
    NSArray *array = @[@{@"funcid":@"5", @"session":[HZUserManager manager].peiziAccountSession}];
    [MYHttp post:kAPIPeiziHost params:array success:^(id response) {
        NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:2];
        if ([response isKindOfClass:[NSArray class]]) {
            NSArray *array = (NSArray *)response;
            for (NSDictionary *dict in array) {
                HZPeiziAccountMoneyModel *model = [HZPeiziAccountMoneyModel mj_objectWithKeyValues:dict];
                [tempArray addObject:model];
            }
        }
        if (tempArray.count > 0) {
            _pMoneyModel = tempArray[0];
        }else {
            _pMoneyModel = [HZPeiziAccountMoneyModel new];
        }
        [self updateTitle:_pCurAccountId];
        [_pPeiziHomeView updateAccontMoneyData:_pMoneyModel];
        [SVProgressHUD dismiss];
    } failure:^(NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain];
    }];
}

@end
